package cn.xinfei.xdecision.common.service.utils;

import cn.xinfei.xdecision.common.utils.constant.SysConstant;
import cn.xinfei.xdecision.common.utils.exception.ApiException;
import cn.xinfei.xdecision.common.utils.exception.enums.ErrorCodeEnum;
import cn.xinfei.xdecision.common.utils.util.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * code生成工具类
 */
@Component
@Slf4j
public class CodeGenerateUtil {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 默认六个字符
     */
    public static final DecimalFormat DF_SIX = new DecimalFormat("000000");

    /**
     * @param prefix  前缀
     * @param pattern 格式
     * @see DateUtils
     * @see SysConstant
     */
    public String generateYMDCode(String prefix, String pattern) {
        if (StringUtils.isEmpty(prefix)) {
            return null;
        } else {
            if (StringUtils.isEmpty(pattern)) {
                pattern = DateUtils.yyyyMMdd;
            }
            String formatDate = new SimpleDateFormat(pattern).format(new Date());
            String redisKye = prefix + ":" + "SYS_CODE_YMD_REDIS_KEY";
            Long no = this.stringRedisTemplate.opsForValue().increment(redisKye);
            expire(redisKye, DateUtils.getCurrent2TodayEndMillisTime() / 1000L);
            return prefix + formatDate + DF_SIX.format(no);
        }
    }

    private void expire(String key, long time) {
        try {
            if (time > 0L) {
                this.stringRedisTemplate.expire(key, time, TimeUnit.SECONDS);
            }
        } catch (Exception e) {
            log.error("code生成工具类报错", e);
            throw new ApiException(ErrorCodeEnum.CODE_GENERATE_ERROR);
        }
    }
}
